package swings.labels;

import change.ItemColorChange;
import com.alibaba.fastjson.JSONObject;
import controllers.ComboButtonControl;
import entity.CommonParam;
import entity.CommonRecord;
import lombok.SneakyThrows;
import swings.buttons.CommonButton;
import swings.frames.CopyRecordFrame;
import swings.frames.EditRecordFrame;
import swings.panels.RecordPanel;
import swings.panels.WorkPanel;
import utils.AESUtils;
import utils.CommonUtils;
import utils.DataManageUtils;
import utils.ImageUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: runoob
 * @date:
 */
public class RecordLabel extends JLabel {

    private JLabel text = new JLabel();
    private JLabel isSkin = new JLabel();
    private JButton choose = new JButton();
    private CommonButton edit = new CommonButton(ImageUtils.operateImg,225,0,30,30);
    private CommonButton copy = new CommonButton(ImageUtils.copyImg,250,0,30,30);
    private WorkPanel workPanel;
    public CommonRecord commonRecord;
    public RecordPanel recordPanel;
    public int id;
    public Boolean isChoose = false;

    public RecordLabel(int id, int y, CommonRecord commonRecord, WorkPanel workPanel, RecordPanel recordPanel) throws IOException {
        this.id = id;
        this.commonRecord = commonRecord;
        this.workPanel = workPanel;
        this.recordPanel = recordPanel;
        setLabel(y);
    }

    private void setLabel(int y) throws IOException {

        Font font = CommonUtils.getFont();
        this.setIcon(ImageUtils.common);
        this.setVerticalTextPosition(JLabel.CENTER);
        this.setHorizontalTextPosition(JLabel.CENTER);
        this.setFont(font);
        this.setForeground(Color.WHITE);
        this.setBounds(5,y,RecordPanel.width-10,30);
        text.setText(commonRecord.getTitle());
        text.setFont(font);
        text.setForeground(Color.WHITE);
        text.setBounds(10,0,280,30);
//        text.setBackground(Color.WHITE);
        //初始化已选择图标
        isSkin.setIcon(new ImageIcon(ItemColorChange.change(ImageUtils.yes)));
        isSkin.setBorder(null);
        isSkin.setBounds(RecordPanel.width-50,5,20,20);
        //初始化选择按钮
        choose.setContentAreaFilled(false);
        choose.setName("" + commonRecord.getTitle());
        choose.setBorder(null);
        choose.setBounds(0,0,RecordPanel.width-10,30);
        choose.addActionListener(new chooseListener());
        edit.addActionListener(new editListener());
        copy.addActionListener(new copyListener());
        //添加鼠标事件
        ComboButtonControl mouse = new ComboButtonControl(choose);
        choose.addMouseListener(mouse);
        edit.setVisible(false);
        copy.setVisible(false);

        this.add(edit);
        this.add(copy);
        this.add(choose);
        this.add(text);
        this.add(new BarLabel());
//        this.add(bg);

    }

    public void addIsChoose(){
//        text.add(isSkin);
        isChoose = true;
        this.setBorder(BorderFactory.createLineBorder(CommonUtils.color, 3, true));
        edit.setVisible(true);
        copy.setVisible(true);
    }

    public void removeIsChoose(){
//        text.remove(isSkin);
        isChoose = false;
        this.setBorder(null);
        edit.setVisible(false);
        copy.setVisible(false);
    }

    private class chooseListener implements ActionListener {

        @SneakyThrows
        @Override
        public void actionPerformed(ActionEvent e) {
            choose();
        }
    }

    public void choose() throws SQLException, IOException, ClassNotFoundException {
        if (!recordPanel.isMultipleChoice){
            addIsChoose();
            setRecordInfo();
            recordPanel.chosenId = id;
            recordPanel.refreshRecordList();
        }else{
            if (isChoose){
                removeIsChoose();
                recordPanel.multipleChoiceMap.remove(id);
            }else {
                addIsChoose();
                recordPanel.multipleChoiceMap.put(id, id);
            }
        }
    }

    private class editListener implements ActionListener {

        @SneakyThrows
        @Override
        public void actionPerformed(ActionEvent e) {
            new EditRecordFrame(recordPanel, id, commonRecord.getTitle());
        }
    }

    private class copyListener implements ActionListener {

        @SneakyThrows
        @Override
        public void actionPerformed(ActionEvent e) {
            new CopyRecordFrame(recordPanel, commonRecord, workPanel);
        }
    }

    public void setRecordInfo() throws SQLException, ClassNotFoundException, IOException {
        workPanel.setUrl(commonRecord.getUrl());
        workPanel.setMethod(commonRecord.getMethod());
        workPanel.secretsPanel.setData(commonRecord);
        workPanel.bodyPanel.setData(commonRecord.getBody());
        workPanel.repBodyPanel.setData(commonRecord.getResult());
        AESUtils aesUtils = new AESUtils();
        String cache = "";
        if (CommonUtils.getJSONType(commonRecord.getResult())){
            JSONObject object = JSONObject.parseObject(commonRecord.getResult());
            if (null != object){
                Set<Map.Entry<String, Object>> objectSet =  object.entrySet();
                for (Map.Entry<String, Object> objectMap : objectSet){
                    if (objectMap.getKey().toLowerCase().equals("data")){
                        cache = CommonUtils.formatJSON(aesUtils.Decrypt(commonRecord.getDataSecret(),commonRecord.getDataSecretIV(),object.getString("data")));
                    }
                }
            }
        }else {
            cache = CommonUtils.formartHTML(commonRecord.getResult());
        }
        workPanel.repDataPanel.setData(cache);
        workPanel.repInfoPanel.setData("");
        workPanel.record = commonRecord;
        Map<String,Integer> valueMap = new HashMap<>();
        valueMap.put("id", commonRecord.getId());
        Connection connection = DataManageUtils.getConnection();
        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setParams(DataManageUtils.getParam(statement, valueMap));
        setHeaders(DataManageUtils.getHeader(statement, valueMap));
        setTemplate(DataManageUtils.getTemplate(statement, valueMap));
        statement.close();
        connection.close();
    }

    public void clearRecordInfo() throws SQLException, ClassNotFoundException, IOException {
        CommonRecord cache = new CommonRecord();
        workPanel.setUrl("");
        workPanel.setMethod("");
        workPanel.secretsPanel.setData(cache);
        workPanel.bodyPanel.textArea.setText("");
        workPanel.repBodyPanel.textArea.setText("");
        workPanel.record = cache;
        Map<String,Integer> valueMap = new HashMap<>();
        valueMap.put("id", 0);
        Connection connection = DataManageUtils.getConnection();
        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setParams(DataManageUtils.getParam(statement, valueMap));
        setHeaders(DataManageUtils.getHeader(statement, valueMap));
        setTemplate(DataManageUtils.getTemplate(statement, valueMap));
        statement.close();
        connection.close();
    }

    public void setParams(ResultSet paramSet) throws SQLException, IOException {
        //结果集指针指到最后一行数据，用于获取结果总数
        paramSet.last();
        int resultSetLength = paramSet.getRow();
        //结果集指针指到开头
        paramSet.beforeFirst();
        //遍历结果集并将数据存入数组
        ArrayList<CommonParam> data = new ArrayList<>();
        for (int m=0;m<resultSetLength;m++){
            CommonParam commonParam = new CommonParam();
            paramSet.next();
            commonParam.setId(paramSet.getInt("id"));
            commonParam.setKey(paramSet.getString("paramkey"));
            commonParam.setValue(paramSet.getString("paramvalue"));
            commonParam.setDescription(paramSet.getString("paramdescription"));
            data.add(commonParam);
        }
        // 关闭链接
        paramSet.close();
        workPanel.paramsPanel.setData(data);
    }

    public void setHeaders(ResultSet headerSet) throws SQLException, IOException {
        //结果集指针指到最后一行数据，用于获取结果总数
        headerSet.last();
        int resultSetLength = headerSet.getRow();
        //结果集指针指到开头
        headerSet.beforeFirst();
        //遍历结果集并将数据存入数组
        ArrayList<CommonParam> data = new ArrayList<>();
        for (int m=0;m<resultSetLength;m++){
            CommonParam commonParam = new CommonParam();
            headerSet.next();
            commonParam.setId(headerSet.getInt("id"));
            commonParam.setKey(headerSet.getString("headerkey"));
            commonParam.setValue(headerSet.getString("headervalue"));
            commonParam.setDescription(headerSet.getString("headerdescription"));
            data.add(commonParam);
        }
        // 关闭链接
        headerSet.close();
        workPanel.headersPanel.setData(data);
    }

    public void setTemplate(ResultSet templateSet) throws SQLException, IOException {
        //结果集指针指到最后一行数据，用于获取结果总数
        templateSet.last();
        int resultSetLength = templateSet.getRow();
        //结果集指针指到开头
        templateSet.beforeFirst();
        //遍历结果集并将数据存入数组
        ArrayList<CommonParam> data = new ArrayList<>();
        for (int m=0;m<resultSetLength;m++){
            CommonParam commonParam = new CommonParam();
            templateSet.next();
            commonParam.setId(templateSet.getInt("id"));
            commonParam.setKey(templateSet.getString("templatekey"));
            commonParam.setValue(templateSet.getString("templatevalue"));
            commonParam.setDescription(templateSet.getString("templatedescription"));
            data.add(commonParam);
        }
        // 关闭链接
        templateSet.close();
        workPanel.templatePanel.setData(data);
    }

    public void refresh(String name) throws IOException {
//        recordPanel.refresh(name);
    }

}

